package com.ruoyi.project.modules.interfaceinfo.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.modules.interfaceinfo.domain.InterfaceInfo;
import com.ruoyi.project.modules.interfaceinfo.mapper.InterfaceInfoMapper;
import com.ruoyi.project.modules.interfaceinfo.request.VirtualUsageReq;
import com.ruoyi.project.modules.interfaceinfo.service.IInterfaceInfoService;
import com.ruoyi.project.modules.interfaceinfo.vo.FieldSourceVo;
import com.ruoyi.project.modules.interfaceinfo.vo.InterfaceParam;
import com.ruoyi.project.modules.parameter.domain.InterfaceParamsFieldRelation;
import com.ruoyi.project.modules.parameter.domain.ParamsFieldRelation;
import com.ruoyi.project.modules.parameter.mapper.InterfaceParamsFieldRelationMapper;
import com.ruoyi.project.modules.parameter.mapper.ParamsFieldRelationMapper;
import com.ruoyi.project.modules.virtualUsageParamSource.domain.VirtualUsageParamSource;
import com.ruoyi.project.modules.virtualUsageParamSource.mapper.VirtualUsageParamSourceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.modules.interfaceinfo.mapper.VirtualUsageMapper;
import com.ruoyi.project.modules.interfaceinfo.domain.VirtualUsage;
import com.ruoyi.project.modules.interfaceinfo.service.IVirtualUsageService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 虚拟用况接口Service业务层处理
 *
 * @author smallrain
 * @date 2021-10-29
 */
@Service
public class VirtualUsageServiceImpl implements IVirtualUsageService {
    @Resource
    private VirtualUsageMapper virtualUsageMapper;
    @Resource
    private InterfaceParamsFieldRelationMapper interfaceParamsFieldRelationMapper;
    @Resource
    private ParamsFieldRelationMapper paramsFieldRelationMapper;

    /**
     * 查询虚拟用况接口
     *
     * @param id 虚拟用况接口主键
     * @return 虚拟用况接口
     */
    @Override
    public VirtualUsage selectVirtualUsageById(Long id) {
        return virtualUsageMapper.selectVirtualUsageById(id);
    }

    /**
     * 查询虚拟用况接口列表
     *
     * @param virtualUsage 虚拟用况接口
     * @return 虚拟用况接口
     */
    @Override
    public List<VirtualUsage> selectVirtualUsageList(VirtualUsage virtualUsage) {
        return virtualUsageMapper.selectVirtualUsageList(virtualUsage);
    }

    /**
     * 新增虚拟用况接口
     *
     * @param virtualUsage 虚拟用况接口
     * @return 结果
     */
    @Override
    public int insertVirtualUsage(VirtualUsage virtualUsage) {
        virtualUsage.setCreateTime(DateUtils.getNowDate());
        return virtualUsageMapper.insertVirtualUsage(virtualUsage);
    }

    /**
     * 修改虚拟用况接口
     *
     * @param virtualUsage 虚拟用况接口
     * @return 结果
     */
    @Override
    public int updateVirtualUsage(VirtualUsage virtualUsage) {
        virtualUsage.setUpdateTime(DateUtils.getNowDate());
        return virtualUsageMapper.updateVirtualUsage(virtualUsage);
    }

    /**
     * 批量删除虚拟用况接口
     *
     * @param ids 需要删除的虚拟用况接口主键
     * @return 结果
     */
    @Override
    public int deleteVirtualUsageByIds(String ids) {
        return virtualUsageMapper.deleteVirtualUsageByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除虚拟用况接口信息
     *
     * @param id 虚拟用况接口主键
     * @return 结果
     */
    @Override
    public int deleteVirtualUsageById(Long id) {
        return virtualUsageMapper.deleteVirtualUsageById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveVirtualUsage(InterfaceInfo interfaceInfo) {
        this.virtualUsageMapper.deleteVirtualUsageByRelationInterfaceId(Collections.singletonList(interfaceInfo.getId()));
        if (CollectionUtil.isNotEmpty(interfaceInfo.getVirtualUsages())) {
            return this.virtualUsageMapper.saveVirtualUsageList(interfaceInfo.getVirtualUsages(), interfaceInfo.getId());
        } else {
            return 1;
        }
    }

    @Override
    public List<VirtualUsage> selectVirtualUsages(VirtualUsage virtualUsage) {
        return this.virtualUsageMapper.selectVirtualUsages(virtualUsage);
    }

    @Resource
    private VirtualUsageParamSourceMapper virtualUsageParamSourceMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveVirtualUsageNew(VirtualUsageReq virtualUsageReq) {
        int maxSortNum = this.virtualUsageMapper.selectMaxSortNum(virtualUsageReq.getRelationInterfaceId()) + 1;
        List<VirtualUsage> virtualUsages = new ArrayList<>();
        for (Long id : virtualUsageReq.getInterfaceId()) {
            VirtualUsage virtualUsage = new VirtualUsage();
            virtualUsage.setRelationInterfaceId(virtualUsageReq.getRelationInterfaceId());
            virtualUsage.setInterfaceId(id);
            virtualUsage.setSortNum((maxSortNum++) + "");
            virtualUsages.add(virtualUsage);
        }
        // 保存虚拟用况
        this.virtualUsageMapper.saveVirtualUsageListNew(virtualUsages);
        boolean isRequired = false;
        InterfaceInfo info = this.interfaceInfoService.selectInterfaceInfoById(virtualUsageReq.getInterfaceId().get(0));
        if ("1".equals(info.getFbType())) {
            InterfaceInfo interfaceInfo = this.interfaceInfoService.selectInterfaceInfoById(virtualUsageReq.getRelationInterfaceId());
            if ("3".equals(interfaceInfo.getFbType()) && "4".equals(interfaceInfo.getOptType())) {
                isRequired = true;
            }
        }
        Map<Long, List<VirtualUsage>> collect = virtualUsages.stream().collect(Collectors.groupingBy(VirtualUsage::getInterfaceId));
        List<InterfaceParamsFieldRelation> interfaceParamsFieldRelationList = this.virtualUsageMapper.queryInterfaceParam(virtualUsages, virtualUsageReq.getType());
        if (CollectionUtil.isNotEmpty(interfaceParamsFieldRelationList)) {
            Iterator<InterfaceParamsFieldRelation> iterator = interfaceParamsFieldRelationList.iterator();
            while (iterator.hasNext()) {
                InterfaceParamsFieldRelation interfaceParamsFieldRelation = iterator.next();
                if (interfaceParamsFieldRelation.getIsInParam().equals("1") &&
                        StringUtils.isNotEmpty(interfaceParamsFieldRelation.getDesignContent())) {
                    iterator.remove();
                    continue;
                }
                List<VirtualUsage> virtualUsageList = collect.get(interfaceParamsFieldRelation.getInterfaceId());
                if (CollectionUtil.isNotEmpty(virtualUsageList)) {
                    interfaceParamsFieldRelation.setInterfaceId(virtualUsageList.get(0).getId());
                    interfaceParamsFieldRelation.setType("3");
                } else {
                    interfaceParamsFieldRelation.setInterfaceId(null);
                    interfaceParamsFieldRelation.setType(null);
                }
                interfaceParamsFieldRelation.setDataRelationId(interfaceParamsFieldRelation.getId());
                interfaceParamsFieldRelation.setDataRelationType("1");
                interfaceParamsFieldRelation.setIsRequiredParent(interfaceParamsFieldRelation.getIsRequired());
                interfaceParamsFieldRelation.setId(null);
                if (isRequired) {
                    interfaceParamsFieldRelation.setIsRequired("Y");
                }
                if (StringUtils.isNotEmpty(interfaceParamsFieldRelation.getDesignContent())) {
                    interfaceParamsFieldRelation.setIsUpdate("N");
                }
            }
            if (interfaceParamsFieldRelationList.size() > 0) {
                // 保存虚拟用况参数
                this.interfaceParamsFieldRelationMapper.batchSave(interfaceParamsFieldRelationList);
                List<ParamsFieldRelation> paramsFieldRelationList = new ArrayList<>();
                List<InterfaceParamsFieldRelation> inParamList = new ArrayList<>();
                // 保存参数字段
                for (InterfaceParamsFieldRelation interfaceParamsFieldRelation : interfaceParamsFieldRelationList) {
                    if (CollectionUtil.isNotEmpty(interfaceParamsFieldRelation.getParamsFieldRelationList())) {
                        for (ParamsFieldRelation paramsFieldRelation : interfaceParamsFieldRelation.getParamsFieldRelationList()) {
                            if (interfaceParamsFieldRelation.getIsInParam().equals("1") &&
                                    StringUtils.isNotEmpty(paramsFieldRelation.getDesignContent())) {
                                continue;
                            }
                            paramsFieldRelation.setDataRelationId(paramsFieldRelation.getId());
                            paramsFieldRelation.setDataRelationType("2");
                            paramsFieldRelation.setId(null);
                            paramsFieldRelation.setIsRequiredParent(paramsFieldRelation.getIsRequired());
                            paramsFieldRelation.setInterfaceDataListId(interfaceParamsFieldRelation.getId());
                            paramsFieldRelationList.add(paramsFieldRelation);
                            if (StringUtils.isNotEmpty(paramsFieldRelation.getDesignContent())) {
                                paramsFieldRelation.setIsUpdate("N");
                            }
                            if (isRequired) {
                                paramsFieldRelation.setIsRequired("Y");
                            }
                        }
                    }
                    if (interfaceParamsFieldRelation.getIsInParam().equals("1")) {
                        inParamList.add(interfaceParamsFieldRelation);
                    }
                }
                if (paramsFieldRelationList.size() > 0) {
                    this.paramsFieldRelationMapper.batchSave(paramsFieldRelationList);
                }
            }
        }
        return 1;
    }

    @Override
    public void updateInterfaceSort(List<VirtualUsage> virtualUsages) {
        this.virtualUsageMapper.updateInterfaceSort(virtualUsages);
    }

    @Resource
    private IInterfaceInfoService interfaceInfoService;

    @Override
    public List<FieldSourceVo> selectFieldSource(Long id, Long processBranchId) {
        List<FieldSourceVo> result = new ArrayList<>();
        VirtualUsageParamSource virtualUsageParamSource = new VirtualUsageParamSource();
        virtualUsageParamSource.setInterfaceId(id);
        virtualUsageParamSource.setProcessBranchId(processBranchId);
        List<VirtualUsageParamSource> virtualUsageParamSources = this.virtualUsageParamSourceMapper.selectVirtualUsageParamSourceList2(virtualUsageParamSource);
        List<Long> ids1 = new ArrayList<>();
        List<Long> ids2 = new ArrayList<>();
        virtualUsageParamSources.forEach(o -> {
            if (o.getType().equals("1")) {
                ids1.add(o.getObjectId());
                ids1.add(o.getSourceobjectId());
            } else {
                ids2.add(o.getObjectId());
                ids2.add(o.getSourceobjectId());
            }
        });
        Map<String, FieldSourceVo> collect1 = new HashMap<>(), collect2 = new HashMap<>();
        if (CollectionUtil.isNotEmpty(ids1)) {
            List<FieldSourceVo> fieldSourceVos = this.virtualUsageMapper.queryFieldSource1(ids1);
            if (CollectionUtil.isNotEmpty(fieldSourceVos)) {
                for (FieldSourceVo fieldSourceVo : fieldSourceVos) {
                    collect1.put(fieldSourceVo.getId() + "1", fieldSourceVo);
                }
            }
        }
        if (CollectionUtil.isNotEmpty(ids2)) {
            List<FieldSourceVo> fieldSourceVos = this.virtualUsageMapper.queryFieldSource2(ids2);
            if (CollectionUtil.isNotEmpty(fieldSourceVos)) {
                for (FieldSourceVo fieldSourceVo : fieldSourceVos) {
                    collect2.put(fieldSourceVo.getId() + "2", fieldSourceVo);
                }
            }
        }
        for (VirtualUsageParamSource usageParamSource : virtualUsageParamSources) {
            FieldSourceVo fieldSourceVo = new FieldSourceVo();
            if (usageParamSource.getType().equals("1")) {
                fieldSourceVo.setObjectType("1");
                FieldSourceVo fieldSourceVo1 = collect1.get(usageParamSource.getObjectId() + "1");
                if (fieldSourceVo1 != null) {
                    fieldSourceVo.setFieldName(fieldSourceVo1.getFieldName());
                    fieldSourceVo.setFieldEnName(fieldSourceVo1.getFieldEnName());
                }
            } else {
                fieldSourceVo.setObjectType("2");
                FieldSourceVo fieldSourceVo1 = collect2.get(usageParamSource.getObjectId() + "2");
                if (fieldSourceVo1 != null) {
                    fieldSourceVo.setFieldName(fieldSourceVo1.getFieldName());
                    fieldSourceVo.setFieldEnName(fieldSourceVo1.getFieldEnName());
                    fieldSourceVo.setParamsName(fieldSourceVo1.getParamsName());
                    fieldSourceVo.setParamsEnName(fieldSourceVo1.getParamsEnName());
                    fieldSourceVo.setInterfaceName(fieldSourceVo1.getInterfaceName());
                }
            }

            if (usageParamSource.getSourceType().equals("1")) {
                fieldSourceVo.setSourceObjectType("1");
                FieldSourceVo fieldSourceVo1 = collect1.get(usageParamSource.getSourceobjectId() + "1");
                if (fieldSourceVo1 != null) {
                    fieldSourceVo.setSourceFieldName(fieldSourceVo1.getFieldName());
                    fieldSourceVo.setSourceFieldEnName(fieldSourceVo1.getFieldEnName());
                    fieldSourceVo.setSourceInterfaceName(fieldSourceVo1.getInterfaceName());
                }
            } else {
                fieldSourceVo.setSourceObjectType("2");
                FieldSourceVo fieldSourceVo1 = collect2.get(usageParamSource.getSourceobjectId() + "2");
                if (fieldSourceVo1 != null) {
                    fieldSourceVo.setSourceFieldName(fieldSourceVo1.getFieldName());
                    fieldSourceVo.setSourceFieldEnName(fieldSourceVo1.getFieldEnName());
                    fieldSourceVo.setSourceParamsName(fieldSourceVo1.getParamsName());
                    fieldSourceVo.setSourceParamsEnName(fieldSourceVo1.getParamsEnName());
                    fieldSourceVo.setSourceInterfaceName(fieldSourceVo1.getInterfaceName());
                }
            }

            result.add(fieldSourceVo);
        }
        return result;
    }

    @Override
    public int updateVirtualUsageModel(VirtualUsage virtualUsage) {
        return this.virtualUsageMapper.updateVirtualUsageModel(virtualUsage);
    }
}
